package com.hiyee.exception;

import com.hiyee.grace.result.ResponseJsonResult;
import com.hiyee.grace.result.ResponseStatusEnum;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一异常拦截处理
 * 返回 json 到前端
 *
 * @author WangBin
 */
@ControllerAdvice
public class GraceExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseJsonResult returnBusinessException(BusinessException e) {
        e.printStackTrace();
        return ResponseJsonResult.exception(e.getResponseStatusEnum());
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public ResponseJsonResult returnBusinessException(MaxUploadSizeExceededException e) {
        e.printStackTrace();
        return ResponseJsonResult.exception(ResponseStatusEnum.UPLOAD_FILE_SIZE_LIMIT);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseJsonResult returnArgumentException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> errMap = getErrors(result);
        return ResponseJsonResult.errorMap(errMap);
    }

    /**
     * 获取参数验证错误信息
     *
     * @param bindingResult
     * @return
     */
    public Map<String, String> getErrors(BindingResult bindingResult)
    {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = bindingResult.getFieldErrors();
        for (FieldError error : errorList) {
            map.put(error.getField(), error.getDefaultMessage());
        }
        return map;
    }

}
